package com.yunsoft.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yunsoft.dao.UserDao;
import com.yunsoft.dao.UserMapper;
import com.yunsoft.dao.impl.UserDaoImpl;
import com.yunsoft.pojo.User;
import com.yunsoft.service.UserService;

@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	@Autowired
	UserDao userDao;
	
	@Override
	public boolean insertUser(String nickName, String country, String province, String city, String sex, int sourceType,
			String openId,String avatarUrl) {
		int result = 0;
		// TODO Auto-generated method stub
		if(sourceType == 1){
			String sql = "select * from User where openId =?";
			User user = jdbcTemplate.queryForObject(sql,new Object[]{openId}, new UserMapper());
			if(user == null) {
				String insertSql = "insert into User(nickName,country,province,city,sex,sourceType,openId,avatarUrl) values(?,?,?,?,?,?,?)";
				result = jdbcTemplate.update(insertSql, new Object[]{nickName,country,province,city,sex,sourceType,openId});
			}else {
				String updateUserSql = "update User set nickName=?,country=?,province=?,city=?,sex=?,sourceType=?,avatarUrl=? where openId=?";
				result = jdbcTemplate.update(updateUserSql, new Object[]{nickName,country,province,city,sex,sourceType,avatarUrl,openId});
			}
		}
		
		if(result == 1){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public User queryUserByOpenId(String OpenId) {
		// TODO Auto-generated method stub
		return jdbcTemplate.queryForObject("select * from User where openId=?",new Object[]{OpenId},new UserMapper());
	}

	@Override
	public User insertWxLoginUser(User u) {
		User queryUser = userDao.findOneByOpenId(u.getOpenId());
		if(queryUser==null){
			return userDao.addUser(u);
		}else {
			queryUser.setNickName(u.getNickName());
			queryUser.setSex(u.getSex());
			queryUser.setCity(u.getCity());
			queryUser.setCountry(u.getCountry());
			queryUser.setAvatarUrl(u.getAvatarUrl());
			queryUser.setProvince(u.getProvince());
			queryUser.setSourceType(u.getSourceType());
			queryUser.setSessionKey(u.getSessionKey());
			return userDao.update(queryUser);
		}
	
	}
	
	
	
	

	}
